package cn.chen.base;

import java.io.Serializable;
import java.util.Comparator;
import java.util.TreeSet;

public class Book implements Serializable,Comparable
{
    private String name;
    private int count;

    public Book(String name, int count) {
        this.name = name;
        this.count = count;
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj) return true;
        if(!(obj instanceof Book)) return false;

        Book book = (Book)obj;

        if(getCount() != book.getCount()) return false;
        return getName().equals(book.getName());
    }

    @Override
    public int hashCode() {
        int result = getName().hashCode();
        result = 31 * result + getCount();
        return result;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", count=" + count +
                '}';
    }

    @Override
    public int compareTo(Object anthor) {
        if(anthor instanceof Book){
            Book book = (Book)anthor;
            int result;
            result = getCount() - book.getCount();

//            result = getName().compareTo(book.getName());

            if(result == 0){
                result = getName().compareTo(book.getName());
            }
            return result;
        }
        return 0;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    Comparator comparator = new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            if(o1 instanceof Book && o2 instanceof Book){
                return ((Book) o1).getCount() - ((Book) o2).getCount();
            }
            return 0;
        }
    };

    TreeSet treeSet = new TreeSet(comparator);

    private void test(){
        treeSet.add(new Book("Java",111));
        treeSet.add(new Book("Python",1));
        treeSet.add(new Book("Scala",14));
        treeSet.add(new Book("C",14));
    }

}
